package cn.wildfire.chat.app.extendsion.classes;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;

/**
 * Create by HEKE, 2019/9/10 21:13
 * TODO 检测版本
 */
public class CheckVersionReq {

    private Activity mActivity;

    private CustomAppUIDialog alertDialog;

    public CheckVersionReq(Activity activity) {
        mActivity = activity;
        versionCheck();
    }

    /**
     * 版本检测
     */
    private void versionCheck() {
        /**
         * modify by HEKE , 2019/8/25 21:23
         * TODO 版本检测
         */
        new AndroidVersionUpdateRequest(CaiBaChatApp.getContext(), new AndroidVersionUpdateRequest.OnAndroidVersionCheckListener() {

            @Override
            public void update(boolean updated, String url) {
                if (updated) {
                    try {
                        alertDialog = TipDialog.showCustomDialog(mActivity, R.string.update_tip_title, R.string.check_update_version, new int[]{R.string.confirm, R.string.cancle_but},
                                CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true, 2, true, new TipDialog.OnMsgTipDialogListener() {
                                    @Override
                                    public void then(boolean confirm,boolean outtouch) {
                                        if (confirm) {
                                            openBrowserThenDownload(mActivity, url);
                                        }
                                    }
                                });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void dismiss() {
        try {
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
                alertDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    private void openBrowserThenDownload(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            mActivity.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(mActivity, "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }

}
